import { supabase } from './supabase';
import type {
  Profile,
  Category,
  Product,
  CartItem,
  Order,
  OrderItem,
  ProductFilters,
  AddToCartData,
  UpdateCartItemData,
  CheckoutFormData,
  ProductFormData,
  CategoryFormData,
  ShippingAddress
} from '@/types/types';

// 用户相关API
export const profileApi = {
  // 获取当前用户档案
  async getCurrentProfile(): Promise<Profile | null> {
    const { data: { user } } = await supabase.auth.getUser();
    if (!user) return null;

    const { data, error } = await supabase
      .from('profiles')
      .select('*')
      .eq('user_id', user.id)
      .order('id', { ascending: true })
      .limit(1);

    if (error) throw error;
    return Array.isArray(data) && data.length > 0 ? data[0] : null;
  },

  // 更新用户档案
  async updateProfile(updates: Partial<Profile>): Promise<Profile> {
    const { data: { user } } = await supabase.auth.getUser();
    if (!user) throw new Error('未登录');

    const { data, error } = await supabase
      .from('profiles')
      .update(updates)
      .eq('user_id', user.id)
      .select()
      .order('id', { ascending: true })
      .limit(1);

    if (error) throw error;
    return Array.isArray(data) && data.length > 0 ? data[0] : null;
  },

  // 获取所有用户（管理员）
  async getAllProfiles(): Promise<Profile[]> {
    const { data, error } = await supabase
      .from('profiles')
      .select('*')
      .order('created_at', { ascending: false });

    if (error) throw error;
    return Array.isArray(data) ? data : [];
  },

  // 更新用户角色（管理员）
  async updateUserRole(userId: string, role: 'user' | 'admin'): Promise<Profile> {
    const { data, error } = await supabase
      .from('profiles')
      .update({ role })
      .eq('user_id', userId)
      .select()
      .order('id', { ascending: true })
      .limit(1);

    if (error) throw error;
    return Array.isArray(data) && data.length > 0 ? data[0] : null;
  }
};

// 分类相关API
export const categoryApi = {
  // 获取所有分类
  async getCategories(): Promise<Category[]> {
    const { data, error } = await supabase
      .from('categories')
      .select('*')
      .order('sort_order', { ascending: true });

    if (error) throw error;
    return Array.isArray(data) ? data : [];
  },

  // 创建分类
  async createCategory(categoryData: CategoryFormData): Promise<Category> {
    const { data, error } = await supabase
      .from('categories')
      .insert(categoryData)
      .select()
      .order('id', { ascending: true })
      .limit(1);

    if (error) throw error;
    return Array.isArray(data) && data.length > 0 ? data[0] : null;
  },

  // 更新分类
  async updateCategory(id: string, updates: Partial<CategoryFormData>): Promise<Category> {
    const { data, error } = await supabase
      .from('categories')
      .update(updates)
      .eq('id', id)
      .select()
      .order('id', { ascending: true })
      .limit(1);

    if (error) throw error;
    return Array.isArray(data) && data.length > 0 ? data[0] : null;
  },

  // 删除分类
  async deleteCategory(id: string): Promise<void> {
    const { error } = await supabase
      .from('categories')
      .delete()
      .eq('id', id);

    if (error) throw error;
  }
};

// 商品相关API
export const productApi = {
  // 获取商品列表
  async getProducts(filters?: ProductFilters): Promise<Product[]> {
    let query = supabase
      .from('products')
      .select(`
        *,
        category:categories(*)
      `)
      .eq('is_active', true);

    if (filters?.category_id) {
      query = query.eq('category_id', filters.category_id);
    }

    if (filters?.min_price) {
      query = query.gte('price', filters.min_price);
    }

    if (filters?.max_price) {
      query = query.lte('price', filters.max_price);
    }

    if (filters?.is_featured !== undefined) {
      query = query.eq('is_featured', filters.is_featured);
    }

    if (filters?.search) {
      query = query.or(`name.ilike.%${filters.search}%,description.ilike.%${filters.search}%`);
    }

    const { data, error } = await query.order('created_at', { ascending: false });

    if (error) throw error;
    return Array.isArray(data) ? data : [];
  },

  // 获取推荐商品
  async getFeaturedProducts(): Promise<Product[]> {
    const { data, error } = await supabase
      .from('products')
      .select(`
        *,
        category:categories(*)
      `)
      .eq('is_featured', true)
      .eq('is_active', true)
      .order('created_at', { ascending: false })
      .limit(8);

    if (error) throw error;
    return Array.isArray(data) ? data : [];
  },

  // 获取单个商品
  async getProduct(id: string): Promise<Product | null> {
    const { data, error } = await supabase
      .from('products')
      .select(`
        *,
        category:categories(*)
      `)
      .eq('id', id)
      .order('id', { ascending: true })
      .limit(1);

    if (error) throw error;
    return Array.isArray(data) && data.length > 0 ? data[0] : null;
  },

  // 创建商品
  async createProduct(productData: ProductFormData): Promise<Product> {
    const { data, error } = await supabase
      .from('products')
      .insert(productData)
      .select()
      .order('id', { ascending: true })
      .limit(1);

    if (error) throw error;
    return Array.isArray(data) && data.length > 0 ? data[0] : null;
  },

  // 更新商品
  async updateProduct(id: string, updates: Partial<ProductFormData>): Promise<Product> {
    const { data, error } = await supabase
      .from('products')
      .update(updates)
      .eq('id', id)
      .select()
      .order('id', { ascending: true })
      .limit(1);

    if (error) throw error;
    return Array.isArray(data) && data.length > 0 ? data[0] : null;
  },

  // 删除商品
  async deleteProduct(id: string): Promise<void> {
    const { error } = await supabase
      .from('products')
      .delete()
      .eq('id', id);

    if (error) throw error;
  },

  // 获取所有商品（管理员）
  async getAllProducts(): Promise<Product[]> {
    const { data, error } = await supabase
      .from('products')
      .select(`
        *,
        category:categories(*)
      `)
      .order('created_at', { ascending: false });

    if (error) throw error;
    return Array.isArray(data) ? data : [];
  }
};

// 购物车相关API
export const cartApi = {
  // 获取购物车商品
  async getCartItems(): Promise<CartItem[]> {
    const { data: { user } } = await supabase.auth.getUser();
    if (!user) return [];

    const { data, error } = await supabase
      .from('cart_items')
      .select(`
        *,
        product:products(*)
      `)
      .eq('user_id', user.id)
      .order('created_at', { ascending: false });

    if (error) throw error;
    return Array.isArray(data) ? data : [];
  },

  // 添加到购物车
  async addToCart(cartData: AddToCartData): Promise<CartItem> {
    const { data: { user } } = await supabase.auth.getUser();
    if (!user) throw new Error('未登录');

    // 检查是否已存在相同商品
    const { data: existing } = await supabase
      .from('cart_items')
      .select('*')
      .eq('user_id', user.id)
      .eq('product_id', cartData.product_id)
      .eq('size', cartData.size || '')
      .eq('color', cartData.color || '')
      .order('id', { ascending: true })
      .limit(1);

    if (existing && existing.length > 0) {
      // 更新数量
      const { data, error } = await supabase
        .from('cart_items')
        .update({ quantity: existing[0].quantity + cartData.quantity })
        .eq('id', existing[0].id)
        .select()
        .order('id', { ascending: true })
        .limit(1);

      if (error) throw error;
      return Array.isArray(data) && data.length > 0 ? data[0] : null;
    } else {
      // 新增商品
      const { data, error } = await supabase
        .from('cart_items')
        .insert({
          ...cartData,
          user_id: user.id
        })
        .select()
        .order('id', { ascending: true })
        .limit(1);

      if (error) throw error;
      return Array.isArray(data) && data.length > 0 ? data[0] : null;
    }
  },

  // 更新购物车商品
  async updateCartItem(id: string, updates: UpdateCartItemData): Promise<CartItem> {
    const { data, error } = await supabase
      .from('cart_items')
      .update(updates)
      .eq('id', id)
      .select()
      .order('id', { ascending: true })
      .limit(1);

    if (error) throw error;
    return Array.isArray(data) && data.length > 0 ? data[0] : null;
  },

  // 删除购物车商品
  async removeFromCart(id: string): Promise<void> {
    const { error } = await supabase
      .from('cart_items')
      .delete()
      .eq('id', id);

    if (error) throw error;
  },

  // 清空购物车
  async clearCart(): Promise<void> {
    const { data: { user } } = await supabase.auth.getUser();
    if (!user) throw new Error('未登录');

    const { error } = await supabase
      .from('cart_items')
      .delete()
      .eq('user_id', user.id);

    if (error) throw error;
  }
};

// 订单相关API
export const orderApi = {
  // 创建订单
  async createOrder(checkoutData: CheckoutFormData, cartItems: CartItem[]): Promise<Order> {
    const { data: { user } } = await supabase.auth.getUser();
    if (!user) throw new Error('未登录');

    // 计算总金额
    const totalAmount = cartItems.reduce((sum, item) => {
      return sum + (item.product?.price || 0) * item.quantity;
    }, 0);

    // 生成订单号
    const orderNumber = `FS${Date.now()}${Math.random().toString(36).substr(2, 4).toUpperCase()}`;

    // 创建订单
    const { data: orderData, error: orderError } = await supabase
      .from('orders')
      .insert({
        user_id: user.id,
        order_number: orderNumber,
        total_amount: totalAmount,
        shipping_address: checkoutData.shipping_address,
        payment_method: checkoutData.payment_method,
        notes: checkoutData.notes || null
      })
      .select()
      .order('id', { ascending: true })
      .limit(1);

    if (orderError) throw orderError;
    const order = Array.isArray(orderData) && orderData.length > 0 ? orderData[0] : null;
    if (!order) throw new Error('创建订单失败');

    // 创建订单商品
    const orderItems = cartItems.map(item => ({
      order_id: order.id,
      product_id: item.product_id,
      product_name: item.product?.name || '',
      product_image: item.product?.images?.[0] || null,
      price: item.product?.price || 0,
      quantity: item.quantity,
      size: item.size || null,
      color: item.color || null
    }));

    const { error: itemsError } = await supabase
      .from('order_items')
      .insert(orderItems);

    if (itemsError) throw itemsError;

    // 清空购物车
    await cartApi.clearCart();

    return order;
  },

  // 获取用户订单
  async getUserOrders(): Promise<Order[]> {
    const { data: { user } } = await supabase.auth.getUser();
    if (!user) return [];

    const { data, error } = await supabase
      .from('orders')
      .select(`
        *,
        order_items(*)
      `)
      .eq('user_id', user.id)
      .order('created_at', { ascending: false });

    if (error) throw error;
    return Array.isArray(data) ? data : [];
  },

  // 获取单个订单
  async getOrder(id: string): Promise<Order | null> {
    const { data, error } = await supabase
      .from('orders')
      .select(`
        *,
        order_items(*)
      `)
      .eq('id', id)
      .order('id', { ascending: true })
      .limit(1);

    if (error) throw error;
    return Array.isArray(data) && data.length > 0 ? data[0] : null;
  },

  // 获取所有订单（管理员）
  async getAllOrders(): Promise<Order[]> {
    const { data, error } = await supabase
      .from('orders')
      .select(`
        *,
        order_items(*),
        profiles!orders_user_id_fkey(nickname, phone)
      `)
      .order('created_at', { ascending: false });

    if (error) throw error;
    return Array.isArray(data) ? data : [];
  },

  // 更新订单状态
  async updateOrderStatus(id: string, status: Order['status']): Promise<Order> {
    const { data, error } = await supabase
      .from('orders')
      .update({ status })
      .eq('id', id)
      .select()
      .order('id', { ascending: true })
      .limit(1);

    if (error) throw error;
    return Array.isArray(data) && data.length > 0 ? data[0] : null;
  }
};

// 统计相关API
export const statsApi = {
  // 获取仪表板统计数据
  async getDashboardStats() {
    const [productsResult, ordersResult, usersResult, revenueResult] = await Promise.all([
      supabase.from('products').select('id', { count: 'exact', head: true }),
      supabase.from('orders').select('id', { count: 'exact', head: true }),
      supabase.from('profiles').select('id', { count: 'exact', head: true }),
      supabase.from('orders').select('total_amount').eq('status', 'paid')
    ]);

    const totalRevenue = Array.isArray(revenueResult.data) 
      ? revenueResult.data.reduce((sum, order) => sum + (order.total_amount || 0), 0)
      : 0;

    // 获取最近订单
    const { data: recentOrders } = await supabase
      .from('orders')
      .select(`
        *,
        profiles!orders_user_id_fkey(nickname, phone)
      `)
      .order('created_at', { ascending: false })
      .limit(5);

    return {
      total_products: productsResult.count || 0,
      total_orders: ordersResult.count || 0,
      total_users: usersResult.count || 0,
      total_revenue: totalRevenue,
      recent_orders: Array.isArray(recentOrders) ? recentOrders : []
    };
  }
};